/*
Designer   : Renyangang

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

	http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package device

import (
	"context"
	"fpga-vboard/logger"
	"fpga-vboard/pins"
	"fpga-vboard/protocol"
	"fpga-vboard/utils"
	"time"
)

const (
	RX_SIGNAME = "diaplayRx"
	TX_SIGNAME = "diaplayTx"
)

func init() {
	config := &UartDisplayConfig{
		DeviceInfo: DeviceInfo{
			Id:   UartDiaply_DEFAULT,
			Type: UartDiaply,
			Name: "Serial Display",
			InputPins: []*pins.PinDef{
				pins.NewPinDef(RX_SIGNAME, 1, pins.PinDirectionInput),
			},
			OutputPins: []*pins.PinDef{
				pins.NewPinDef(TX_SIGNAME, 1, pins.PinDirectionOutput),
			},
			IsOptional: true,
			Enable:     false,
		},
		UartConfig: &protocol.UARTConfig{
			Name:     "/dev/ttyUSB0",
			BaudRate: 115200,
			DataBits: 8,
			StopBits: 1,
			Parity:   protocol.ParityNone,
		},
	}
	RegisterDev(config)
}

type UartDisplay struct {
	*DeviceBase
	uart        *protocol.UART
	ctx         context.Context
	displayProc *utils.RunProc
	IsRunning   bool
}

func NewUartDisplay(config *UartDisplayConfig) *UartDisplay {
	return &UartDisplay{
		DeviceBase: &DeviceBase{
			Config: config,
		},
		uart:      protocol.NewUART(config.UartConfig),
		IsRunning: false,
	}
}

func (ud *UartDisplay) Start(ctx context.Context) error {
	ud.ctx = ctx
	ud.IsRunning = true
	ud.uart.SetMainClockFrequency(GlobalInfoInstance.ClockFrequency)
	if ud.Config.(*UartDisplayConfig).ShowTerminal {
		proc, err := utils.StartSerialDisplay()
		if err != nil {
			logger.FatalEvent("start serial display subprocess failed: %v", err)
			return err
		}
		ud.displayProc = proc
	}
	go ud.readLoop()
	return nil
}

func (ud *UartDisplay) Stop(ctx context.Context) {
	ud.IsRunning = false
	ud.displayProc.Kill()
	ud.displayProc.Wait()
}

func (ud *UartDisplay) Run(ctx context.Context) {
	if GlobalInfoInstance.ResetState {
		ud.SetPinBool(TX_SIGNAME, ud.uart.Run(ud.GetPinBool(RX_SIGNAME)))
	}
}

func (ud *UartDisplay) readLoop() {
	for ud.IsRunning {
		select {
		case b := <-ud.uart.ReadChan:
			ud.displayProc.SendByte(b)
		default:
			time.Sleep(time.Microsecond * 10)
		}
	}
}
